<template>
  <div class="doctor-diagnosis-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>医生诊疗</h1>
      <div v-if="patientInfo" class="patient-info">
        患者姓名: {{ patientInfo.realName }}
      </div>
    </div>

    <!-- 标签页导航 -->
    <el-tabs v-model="activeTab" class="tab-navigation">
      <el-tab-pane label="病案首页" name="medical-record"></el-tab-pane>
  <el-tab-pane label="开立申请" name="exam-request"></el-tab-pane>
      <el-tab-pane label="门诊确诊" name="diagnosis"></el-tab-pane>
      <el-tab-pane label="开设处方" name="prescription"></el-tab-pane>
      <el-tab-pane label="费用查询" name="fee-query"></el-tab-pane>
    </el-tabs>

    <!-- 标签页内容：新增外层滚动容器，控制超宽内容横向滚动 -->
    <div class="tab-content-wrapper">
      <div class="tab-content">
        <!-- 病案首页内容 -->
        <div v-if="activeTab === 'medical-record'" class="tab-panel">
          <el-card shadow="hover" class="home-card">
            <!-- 1. 基础信息：将固定列数改为响应式布局，小屏幕自动换行 -->
            <el-form :model="form" label-width="100px" class="home-form">
              <el-row :gutter="20" class="base-info-row">
                <!-- 用xs/sm断点控制列宽，小屏幕占满行，大屏幕分4列 -->
                <el-col :xs="24" :sm="12" :md="6">
                  <el-form-item label="病例号">
                    <el-input v-model="form.caseNo" placeholder="请输入病例号" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="6">
                  <el-form-item label="患者姓名">
                    <el-input v-model="form.patientName" placeholder="请输入患者姓名" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="6">
                  <el-form-item label="性别">
                    <el-radio-group v-model="form.gender">
                      <el-radio label="男">男</el-radio>
                      <el-radio label="女">女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="6">
                  <el-form-item label="年龄">
                    <el-input v-model="form.age" placeholder="请输入年龄" />
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 文本域表单：保持原结构，通过容器控制宽度 -->
              <el-form-item label="主诉">
                <el-input v-model="form.chiefComplaint" type="textarea" :rows="2" placeholder="请输入主诉" />
              </el-form-item>
              <el-form-item label="现病史">
                <el-input v-model="form.presentIllness" type="textarea" :rows="2" placeholder="请输入现病史" />
              </el-form-item>
              <el-form-item label="现病治疗情况">
                <el-input v-model="form.treatment" type="textarea" :rows="2" placeholder="请输入现病治疗情况" />
              </el-form-item>
              <el-form-item label="既往史">
                <el-input v-model="form.pastHistory" type="textarea" :rows="2" placeholder="请输入既往史" />
              </el-form-item>
              <el-form-item label="过敏史">
                <el-input v-model="form.allergy" type="textarea" :rows="2" placeholder="请输入过敏史" />
              </el-form-item>
              <el-form-item label="体格检查">
                <el-input v-model="form.physicalExam" type="textarea" :rows="2" placeholder="请输入体格检查结果" />
              </el-form-item>

              <!-- 2. 西医诊断表格：移除固定min-width，改用max-width+滚动，优化列宽分配 -->
              <div class="diag-table-title">西医诊断</div>
              <!-- 表格外层加滚动容器，避免表格超宽导致页面整体变宽 -->
              <div class="diag-table-container">
                <el-table 
                  :data="form.diagnosisList" 
                  stripe 
                  border 
                  size="small" 
                  style="width: 100%;" 
                >
                  <el-table-column width="50" label="选择"> <!-- 增加label，提升可读性 -->
                    <template #default="{ row }">
                      <el-checkbox v-model="row.checked" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="icd" label="ICD编码" width="120" /> <!-- 微调宽度，适配编码长度 -->
                  <el-table-column prop="name" label="名称" min-width="200"> <!-- 用min-width保证名称显示，避免挤压 -->
                    <template #default="{ row }">
                      <div 
                        class="diagnosis-name" 
                        :title="row.name"
                      >
                        {{ row.name }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="date" label="发病时间" width="140" /> <!-- 适配日期格式长度 -->
                  <el-table-column label="操作" width="100"> <!-- 增加宽度，避免按钮换行 -->
                    <template #default="{ $index }">
                      <el-button size="small" type="danger" @click="removeDiag($index)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div class="table-btn-bar">
                <el-button size="small" :icon="Plus" @click="addDiag">增加</el-button>
              </div>

              <!-- 3. 检查建议 & 注意事项 -->
              <el-form :model="form" label-width="100px" class="home-form" style="margin-top: 20px;">
                <el-form-item label="检查建议">
                  <el-input v-model="form.examAdvice" type="textarea" :rows="2" placeholder="请输入检查建议" />
                </el-form-item>
                <el-form-item label="注意事项">
                  <el-input v-model="form.notice" type="textarea" :rows="2" placeholder="请输入注意事项" />
                </el-form-item>
              </el-form>

              <!-- 4. 底部按钮 -->
              <div class="footer-bar">
                <el-button type="primary" @click="handleSave">保存</el-button>
                <el-button @click="handleReset">重置</el-button>
              </div>
            </el-form>
          </el-card>
        </div>

        <!-- 处置/开设处方标签内容（内嵌组件，不切换路由） -->
        <div v-else-if="activeTab === 'prescription'" class="tab-panel">
          <el-card shadow="hover" class="home-card">
            <disposal-request-tab />
          </el-card>
        </div>
        <div v-else-if="activeTab === 'exam-request'" class="tab-panel">
          <el-card shadow="hover" class="home-card">
            <check-request-tab />
          </el-card>
        </div>
        <div v-else-if="activeTab === 'fee-query'" class="tab-panel">
          <el-card shadow="hover" class="home-card">
            <charge-tab />
          </el-card>
        </div>
        <div v-else-if="activeTab === 'diagnosis'" class="tab-panel">
          <el-card shadow="hover" class="home-card">
            <outpatient-diagnosis-tab />
          </el-card>
        </div>
        <!-- 其他标签页内容（默认占位） -->
        <div v-else class="tab-panel">
          <el-card shadow="hover" class="blank-card">
            <div class="blank-content">
              <el-empty description="功能开发中..."></el-empty>
            </div>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
// 脚本逻辑不变，保持原功能
import { reactive, ref, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import diseaseApi from '@/api/disease'
import registerApi from '@/api/register'
import patientApi from '@/api/patient'
import DisposalRequestTab from '@/components/DisposalRequestTab.vue'
import CheckRequestTab from '@/components/CheckRequestTab.vue'
import OutpatientDiagnosisTab from '@/components/OutpatientDiagnosisTab.vue'
import ChargeTab from '@/components/ChargeTab.vue'
const route = useRoute()
const activeTab = ref('medical-record')
const patientInfo = ref(null)

const form = reactive({
  caseNo: '',
  patientName: '',
  gender: '男',
  age: '',
  chiefComplaint: '',
  presentIllness: '',
  treatment: '',
  pastHistory: '',
  allergy: '',
  physicalExam: '',
  examAdvice: '',
  notice: '',
  diagnosisList: []
})

const loadPatientInfo = async () => {
  try {
    const patientId = route.query.patientId
    console.log('尝试加载患者信息，ID:', patientId)
    if (patientId) {
      const response = await registerApi.getById(patientId)
      if (response && response.data) {
        patientInfo.value = response.data
        form.patientName = response.data.realName || ''
        form.caseNo = response.data.caseNumber || ''
        form.gender = response.data.gender || '男'
        form.age = response.data.age || ''
        console.log('患者信息加载成功:', patientInfo.value)

        // 新增：依据register_id查询病案信息
        const medicalRecordRes = await patientApi.getMedicalRecordByRegisterId(patientId)
        if (medicalRecordRes && Array.isArray(medicalRecordRes.data) && medicalRecordRes.data.length > 0) {
          const mr = medicalRecordRes.data[0]
          // 填充表单内容
          form.chiefComplaint = mr.readme || ''
          form.presentIllness = mr.present || ''
          form.treatment = mr.presentTreat || ''
          form.pastHistory = mr.history || ''
          form.allergy = mr.allergy || ''
          form.physicalExam = mr.physique || ''
          form.examAdvice = mr.proposal || ''
          form.notice = mr.careful || ''
          // 诊断列表（如有）
          // 如果后端 diagnosis 字段是字符串或数组，可按需处理
          if (Array.isArray(mr.diagnosisList)) {
            form.diagnosisList.forEach(item => {
              item.checked = mr.diagnosisList.includes(item.id)
            })
          }
        }
      } else {
        console.warn('患者信息响应格式异常:', response)
        ElMessage.warning('患者信息格式异常')
      }
    } else {
      console.log('未提供患者ID')
    }
  } catch (error) {
    console.error('加载患者信息失败:', error)
    ElMessage.error('加载患者信息失败: ' + (error.message || '未知错误'))
  }
}

const loadDiseaseList = async () => {
  try {
    const response = await diseaseApi.getAll()
    if (response && response.data) {
      form.diagnosisList = response.data.map(disease => ({
        id: disease.id,  // 添加id字段
        checked: false,
        icd: disease.diseaseICD,
        name: disease.diseaseName,
        date: new Date().toLocaleDateString('zh-CN')
      }))
    }
  } catch (error) {
    console.error('加载疾病列表失败:', error)
    ElMessage.error('加载疾病列表失败')
    form.diagnosisList = [
      { checked: false, icd: 'A00', name: '霍乱', date: '2016.3.5' },
      { checked: false, icd: 'A01', name: '伤寒和副伤寒', date: '2016.3.2' },
      { checked: false, icd: 'A02', name: '其他沙门氏菌感染', date: '2016.3.1' },
      { checked: false, icd: 'A03', name: '志贺菌病', date: '2016.3.1' }
    ]
  }
}

// 将处置申请组件挂载（在tab中显示）
const components = {
  DisposalRequestTab
}

function addDiag() {
  form.diagnosisList.push({ 
    id: null,  // 添加id字段
    checked: false, 
    icd: '', 
    name: '', 
    date: new Date().toLocaleDateString('zh-CN') 
  })
}
function removeDiag(index) {
  form.diagnosisList.splice(index, 1)
}

async function handleSave() {
  try {
    // 构建完整的病案数据，根据后端字段名称进行映射
    const medicalRecordData = {
      registerId: patientInfo.value?.id,
      readme: form.chiefComplaint,           // 主诉映射到readme
      present: form.presentIllness,          // 现病史映射到present
      presentTreat: form.treatment,          // 现病治疗情况映射到presentTreat
      history: form.pastHistory,             // 既往史映射到history
      allergy: form.allergy,                 // 过敏史保持一致
      physique: form.physicalExam,           // 体格检查映射到physique
      proposal: form.examAdvice,             // 检查建议映射到proposal
      careful: form.notice,                  // 注意事项映射到careful
      // 传递诊断的id列表
      diagnosisList: form.diagnosisList.filter(item => item.checked).map(item => item.id)
    }
    
    console.log('准备保存的病案数据(映射后):', medicalRecordData)
    const res = await patientApi.createMedicalRecord(medicalRecordData)
    
    if (res.success || res.code === 200) {
      ElMessage.success('病案首页已成功保存')
    } else {
      ElMessage.error(`保存失败：${res.message || '未知错误'}`)
    }
  } catch (error) {
    console.error('保存病案首页失败:', error)
    ElMessage.error(`保存失败：${error.message || '未知错误'}`)
  }
}
function handleReset() {
  Object.assign(form, {
    caseNo: patientInfo.value?.caseNumber || '',
    patientName: patientInfo.value?.realName || '',
    gender: patientInfo.value?.gender || '男',
    age: patientInfo.value?.age || '',
    chiefComplaint: '',
    presentIllness: '',
    treatment: '',
    pastHistory: '',
    allergy: '',
    physicalExam: '',
    examAdvice: '',
    notice: ''
  })
}

onMounted(() => {
  loadPatientInfo()
  loadDiseaseList()
})

// 监听路由参数变化，确保从其他页面跳转过来时能正确加载患者信息
watch(() => route.query.patientId, (newPatientId) => {
  if (newPatientId) {
    console.log('路由参数变化，重新加载患者信息')
    loadPatientInfo()
  }
})
</script>

<style lang="scss" scoped>
.doctor-diagnosis-container {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
  /* 移除原overflow-x:auto，改由内层容器控制滚动 */
}

.page-header {
  background-color: #409eff;
  color: white;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  /* 移除固定min-width，让标题栏自适应页面宽度 */
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
}

.patient-info {
  font-size: 16px;
  font-weight: 500;
  /* 小屏幕下自动换行，避免挤压标题 */
  white-space: normal;
}

.tab-navigation {
  margin-bottom: 20px;
  /* 移除固定min-width，让标签栏自适应 */
}

/* 新增：标签内容外层滚动容器，控制超宽内容仅在内部横向滚动 */
.tab-content-wrapper {
  width: 100%;
  overflow-x: auto; /* 仅在内容超宽时显示横向滚动条 */
  scrollbar-width: thin; /* 优化滚动条样式（火狐） */
  -ms-overflow-style: none; /* 隐藏IE滚动条 */
}

/* 隐藏Chrome默认滚动条，美化体验 */
.tab-content-wrapper::-webkit-scrollbar {
  height: 6px;
}
.tab-content-wrapper::-webkit-scrollbar-thumb {
  background-color: #c0c4cc;
  border-radius: 3px;
}
.tab-content-wrapper::-webkit-scrollbar-track {
  background-color: #f5f5f5;
}

.tab-content {
  width: 100%;
  /* 移除固定min-width，让内容自适应容器 */
}

.tab-panel {
  width: 100%;
  /* 移除固定min-width，避免强制拉伸 */
}

.home-card {
  background: #fff;
  border-radius: 8px;
  width: 100%;
  overflow: hidden;
}

/* 基础信息行：优化响应式布局，避免小屏幕横向溢出 */
.base-info-row {
  margin-bottom: 16px;
}

/* 诊断表格容器：限制表格最大宽度，配合外层滚动 */
.diag-table-container {
  width: 100%;
  max-width: 1200px; /* 限制表格最大宽度，避免极端情况下过宽 */
  margin: 0 auto; /* 居中显示，提升美观度 */
  overflow-x: auto; /* 表格内部超宽时，仅表格区域滚动（可选，根据需求） */
}

.diagnosis-name {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  /* 小屏幕下允许换行，避免挤压其他列 */
  @media (max-width: 768px) {
    white-space: normal;
    word-break: break-all; /* 强制换行，避免中文单词截断 */
  }
}

.diag-table-title {
  margin: 20px 0 8px 0;
  font-size: 16px;
  font-weight: 600;
}

.table-btn-bar {
  text-align: right;
  margin-top: 8px;
}

.footer-bar {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  gap: 16px; /* 增加按钮间距，避免挤压 */
}

.blank-card {
  background: #fff;
  border-radius: 8px;
  padding: 40px;
  text-align: center;
}

.blank-content {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

/* 适配小屏幕（手机）：优化表单和按钮样式 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .el-form-item label {
    font-size: 14px;
  }

  .el-input, .el-radio {
    font-size: 14px;
  }

  .footer-bar {
    flex-direction: column;
    align-items: center;
  }

  .footer-bar .el-button {
    width: 100%;
    margin-bottom: 8px;
  }
}
.tab-content-wrapper,
.tab-content,
.tab-panel {
  max-width: 1300px;
  margin: 0 auto;
}
</style>